<template>
  <div style="overflow-y: hidden; background: #fff; border-radius: 4px">
    <px-tabs
      v-model="activeTab"
      class="equipment-tabs"
      style="margin-bottom: 10px; margin-left: 16px; background: none"
      @tab-change="activeTabChange"
    >
      <px-tab-pane v-for="(item, index) in tabPaneList" :key="index" :name="item.name">
        <template #label>
          <p class="pane-bottom">{{ item.label }}</p>
          <p class="pane-line" />
        </template>
      </px-tab-pane>
    </px-tabs>
    <div class="op-btns" style="padding: 6px 16px">
      <px-radio-group v-model="reportType" style="align-items: baseline; margin-right: 20px" @change="reportTypeChange()">
        <px-radio-button label="monthly">月报表</px-radio-button>
        <px-radio-button label="daily">日报表</px-radio-button>
      </px-radio-group>
      <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" inline label-width="90px">
        <px-form-item v-if="reportType == 'monthly'" label="年份" prop="year">
          <px-select v-model="queryParams.year" placeholder="请选择年份">
            <px-option v-for="item in yearList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item v-if="reportType == 'monthly'" label="月份" prop="month">
          <px-select v-model="queryParams.month" placeholder="请选择年份">
            <px-option v-for="item in monthList" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item v-if="reportType == 'daily'" label="日期" prop="date">
          <px-date-picker v-model="queryParams.date" value-format="YYYY-MM-DD" format="YYYY-MM-DD" type="date" placeholder="请选择日期" />
        </px-form-item>
        <px-form-item class="option-item">
          <px-button type="primary" @click="searchAction">查询</px-button>
          <px-button v-has="'MACHINE_REPORT_VOC_WASTEGAS_EXPORT'" type="primary" plain @click="exportAction">导出</px-button>
          <!-- <px-button @click="resetQuery">重置</px-button> -->
        </px-form-item>
      </px-form>
    </div>
    <div>
      <echartsChart ref="lineRef" :boxShadow="false" :options="lineOptions" />
    </div>

    <div class="title-content">
      <div v-if="reportType == 'monthly'" class="title">烟气排放连续监测日平均值月报</div>
      <div v-if="reportType == 'daily'" class="title">烟气排放连续监测小时平均值日报</div>
      <div class="sub-text">排放源名称：&nbsp;STIC北方集成电路技术创新中心</div>
      <div class="sub-text">排放源编号：&nbsp;<px-input v-model="exhaustSource.itemDesc" type="text" style="width: 180px" @blur="saveSource" /></div>
    </div>
    <div class="iframe-content">
      <iframe id="reportFrame" :src="templateUrl" width="100%" height="100%" frameborder="0" />
    </div>
    <ReTeleport>
      <div class="footer-btns">
        <div class="right"><px-button v-has="'MACHINE_REPORT_VOC_WASTEGAS_SUBMIT'" type="primary" @click="submitAction">提交</px-button></div>
      </div>
    </ReTeleport>
  </div>
</template>

<script setup lang="ts">
import { deleteReportRecord } from "@/api/report";
import { queryNameByTypeCodeAndValue } from "@/api/modules/operation";
import { queryExhauseMeterList } from "@/api/machineClass";
import { dataUpdate } from "@/api/system/dictData";
import { onMounted, reactive, toRefs, ref, computed, nextTick } from "vue";
import { PxMessage, PxMessageBox, PxLoading } from "px-ui";
import { useRouter, useRoute } from "vue-router";
import { useNav } from "@/layout/hooks/useNav";
import dayjs from "dayjs";
import { getToken } from "@/utils/auth";
import ReTeleport from "@/components/ReTeleport";
import echartsChart from "@/views/common/components/echartsChart/index.vue";

defineOptions({
  name: "MACHINE_AR"
});

const { username } = useNav();
const router = useRouter();
const route = useRoute();

const codeNameList = {
  VOC进口: [
    {
      name: "CH4 mg/nm3",
      code: "MICH_FGE_CH4"
    },
    {
      name: "CH4 折算mg/nm3",
      code: "MICH_FGE_CH4_Z"
    },
    {
      name: "CH4 t/d",
      code: "MICH_FGE_CH4_TD"
    },
    {
      name: "NMHC mg/nm3",
      code: "MICH_FGE_NMHC"
    },
    {
      name: "NMHC 折算mg/nm3",
      code: "MICH_FGE_NMHC_Z"
    },
    {
      name: "NMHC t/d",
      code: "MICH_FGE_NMHC_TD"
    },
    {
      name: "THC mg/nm3",
      code: "MICH_FGE_THC"
    },
    {
      name: "THC 折算mg/nm3",
      code: "MICH_FGE_THC_Z"
    },
    {
      name: "THC t/d",
      code: "MICH_FGE_THC_TD"
    },
    {
      name: "流量",
      code: "MICH_FGE_Flow"
    },
    {
      name: "O2%",
      code: "MICH_FGE_O2"
    },
    {
      name: "温度",
      code: "MICH_FGE_SMKTT"
    },
    {
      name: "水份含量%",
      code: "MICH_FGE_HIT"
    }
  ],
  VOC出口: [
    {
      name: "CH4 mg/nm3",
      code: "MICH_FGE_CH4"
    },
    {
      name: "CH4 折算mg/nm3",
      code: "MICH_FGE_CH4_Z"
    },
    {
      name: "CH4 t/d",
      code: "MICH_FGE_CH4_TD"
    },
    {
      name: "NMHC mg/nm3",
      code: "MICH_FGE_NMHC"
    },
    {
      name: "NMHC 折算mg/nm3",
      code: "MICH_FGE_NMHC_Z"
    },
    {
      name: "NMHC t/d",
      code: "MICH_FGE_NMHC_TD"
    },
    {
      name: "THC mg/nm3",
      code: "MICH_FGE_THC"
    },
    {
      name: "THC 折算mg/nm3",
      code: "MICH_FGE_THC_Z"
    },
    {
      name: "THC t/d",
      code: "MICH_FGE_THC_TD"
    },
    {
      name: "流量",
      code: "MICH_FGE_Flow"
    },
    {
      name: "O2%",
      code: "MICH_FGE_O2"
    },
    {
      name: "温度",
      code: "MICH_FGE_SMKTT"
    },
    {
      name: "水份含量%",
      code: "MICH_FGE_HIT"
    }
  ],
  VOC中酸碱: [
    {
      name: "颗粒物 mg/nm3",
      code: "MICH_FGE_DUST"
    },
    {
      name: "颗粒物 折算mg/nm3",
      code: "MICH_FGE_DUST_Z"
    },
    {
      name: "颗粒物 t/d",
      code: "MICH_FGE_DUST_TD"
    },
    {
      name: "SO2 mg/nm3",
      code: "MICH_FGE_S02"
    },
    {
      name: "SO2 折算mg/nm3",
      code: "MICH_FGE_S02_Z"
    },
    {
      name: "SO2 t/d",
      code: "MICH_FGE_S02_TD"
    },
    {
      name: "NOX mg/nm3",
      code: "MICH_FGE_NOX"
    },
    {
      name: "NOX 折算mg/nm3",
      code: "MICH_FGE_NOX_Z"
    },
    {
      name: "NOX t/d",
      code: "MICH_FGE_NOX_TD"
    },
    {
      name: "CO mg/nm3",
      code: "MICH_FGE_CO"
    },
    {
      name: "CO 折算mg/nm3",
      code: "MICH_FGE_CO_Z"
    },
    {
      name: "CO t/d",
      code: "MICH_FGE_CO_TD"
    },
    {
      name: "流量",
      code: "MICH_FGE_Flow"
    },
    {
      name: "O2%",
      code: "MICH_FGE_O2"
    },
    {
      name: "温度",
      code: "MICH_FGE_SMKTT"
    },
    {
      name: "水份含量%",
      code: "MICH_FGE_HIT"
    },
    {
      name: "负荷%",
      code: "MICH_FGE_FH"
    }
  ],
  SEX中酸碱: [
    {
      name: "颗粒物 mg/nm3",
      code: "MICH_FGE_DUST"
    },
    {
      name: "颗粒物 折算mg/nm3",
      code: "MICH_FGE_DUST_Z"
    },
    {
      name: "颗粒物 t/d",
      code: "MICH_FGE_DUST_TD"
    },
    {
      name: "SO2 mg/nm3",
      code: "MICH_FGE_S02"
    },
    {
      name: "SO2 折算mg/nm3",
      code: "MICH_FGE_S02_Z"
    },
    {
      name: "SO2 t/d",
      code: "MICH_FGE_S02_TD"
    },
    {
      name: "NOX mg/nm3",
      code: "MICH_FGE_NOX"
    },
    {
      name: "NOX 折算mg/nm3",
      code: "MICH_FGE_NOX_Z"
    },
    {
      name: "NOX t/d",
      code: "MICH_FGE_NOX_TD"
    },
    {
      name: "CO mg/nm3",
      code: "MICH_FGE_CO"
    },
    {
      name: "CO 折算mg/nm3",
      code: "MICH_FGE_CO_Z"
    },
    {
      name: "CO t/d",
      code: "MICH_FGE_CO_TD"
    },
    {
      name: "NO2 mg/nm3",
      code: "MICH_FGE_NO2"
    },
    {
      name: "NO2 折算mg/nm3",
      code: "MICH_FGE_NO2_Z"
    },
    {
      name: "NO2 t/d",
      code: "MICH_FGE_NO2_TD"
    },
    {
      name: "NH3 mg/nm3",
      code: "MICH_FGE_NH3"
    },
    {
      name: "NH3 折算mg/nm3",
      code: "MICH_FGE_NH3_Z"
    },
    {
      name: "NH3 t/d",
      code: "MICH_FGE_NH3_TD"
    },
    {
      name: "HCL mg/nm3",
      code: "MICH_FGE_HCL"
    },
    {
      name: "HCL 折算mg/nm3",
      code: "MICH_FGE_HCL_Z"
    },
    {
      name: "HCL t/d",
      code: "MICH_FGE_HCL_TD"
    },
    {
      name: "HF mg/nm3",
      code: "MICH_FGE_HF"
    },
    {
      name: "HF 折算mg/nm3",
      code: "MICH_FGE_HF_Z"
    },
    {
      name: "HF t/d",
      code: "MICH_FGE_HF_TD"
    },
    {
      name: "NO mg/nm3",
      code: "MICH_FGE_NO"
    },
    {
      name: "NO 折算mg/nm3",
      code: "MICH_FGE_NO_Z"
    },
    {
      name: "NO t/d",
      code: "MICH_FGE_NO_TD"
    },
    {
      name: "流量",
      code: "MICH_FGE_Flow"
    },
    {
      name: "O2%",
      code: "MICH_FGE_O2"
    },
    {
      name: "温度",
      code: "MICH_FGE_SMKTT"
    },
    {
      name: "水份含量%",
      code: "MICH_FGE_HIT"
    }
  ]
};

const lineRef = ref();
const lineOptions = ref();
const templateUrl = ref();

const reportType = ref("monthly"); //日报表、月报表
const exhaustSource = ref({});

const queryParams = reactive({
  year: new Date().getFullYear(),
  month: new Date().getMonth() + 1 + "",
  date: dayjs()
});

const yearList = ref([]);
const monthList = ref([
  {
    label: "1月",
    value: "1"
  },
  {
    label: "2月",
    value: "2"
  },
  {
    label: "3月",
    value: "3"
  },
  {
    label: "4月",
    value: "4"
  },
  {
    label: "5月",
    value: "5"
  },
  {
    label: "6月",
    value: "6"
  },
  {
    label: "7月",
    value: "7"
  },
  {
    label: "8月",
    value: "8"
  },
  {
    label: "9月",
    value: "9"
  },
  {
    label: "10月",
    value: "10"
  },
  {
    label: "11月",
    value: "11"
  },
  {
    label: "12月",
    value: "12"
  }
]);
const activeTab = ref("VOC进口");
const tabPaneList = ref([
  {
    label: "VOC进口",
    name: "VOC进口"
  },
  {
    label: "VOC出口",
    name: "VOC出口"
  },
  {
    label: "VOC中酸碱",
    name: "VOC中酸碱"
  },
  {
    label: "SEX中酸碱",
    name: "SEX中酸碱"
  }
]);
const activeTabChange = () => {
  // template url 查询条件修改
  getUrl();
};
const reportTypeChange = () => {
  // template url 查询条件修改
  getUrl();
};
const submitAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().verifyAndWriteReport()", "*");
};
// importExcel_Clean清空导入
// importExcel_Append 增量导入
// importExcel_Cover 覆盖导入
const importAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().importExcel_Cover()", "*");
};
const exportAction = () => {
  document.getElementById("reportFrame").contentWindow.postMessage("_g().exportReportToExcel('simple')", "*");
};
const deleteAction = () => {
  PxMessageBox.confirm(`是否该条记录数据？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteReportRecord({ ids: [route.query.id] });
      PxMessage.success("删除成功");
      templateUrl.value = `${window.location.protocol}//${window.location.hostname}:8443/webroot/decision/view/report?viewlet=${route.query.template}&user=${username.value}&__pi__=false`;
      localStorage.setItem("listen_report_record_delete", "true");
      setTimeout(() => {
        window.close();
      }, 1500);
    })
    .catch(() => {});
  //window.close()
};
const printAction = () => {
  // document.getElementById('reportFrame').contentWindow.contentPane.noClientPrint(true, true)();
  // let config = JSON.stringify({
  //   printUrl: `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report`,
  //   printType: 0, // 1
  //   isPopUp: true,
  //   pageType: 0,
  //   data: {
  //     reportlets:[{reportlet: `${decodeURIComponent(decodeURIComponent(route.query.template))}`, cmd: 'save_w_content', op: 'write', singleCode: route.query.singleCode}]
  //   }
  // })
  // // console.log('config:' + JSON.stringify(config));
  // // let config = JSON.stringify({ url: templateUrl.value, isPopUp: true });
  // //doURLPrint doURLPDFPrint
  // document.getElementById("reportFrame").contentWindow.postMessage(`FR.doURLPrint(${config})`, "*");
  document.getElementById("reportFrame").contentWindow.postMessage(`_g().noClientPrint(true,true)`, "*");
};
const { VITE_FANRUAN_BASE_URL } = import.meta.env;
const getUrl = () => {
  let tpName = "";
  let dictCode = "";
  if (reportType.value == "monthly") {
    if (activeTab.value == "VOC进口") {
      tpName = encodeURIComponent(encodeURIComponent("voc/VOC废气在线监测台账-月.cpt"));
      dictCode = "MIC_EXHAUST_SOURCE01";
    }
    if (activeTab.value == "VOC出口") {
      tpName = encodeURIComponent(encodeURIComponent("voc/VOC废气在线监测台账-月1.cpt"));
      dictCode = "MIC_EXHAUST_SOURCE02";
    }
    if (activeTab.value == "VOC中酸碱") {
      tpName = encodeURIComponent(encodeURIComponent("voc/VOC废气在线监测台账-月2.cpt"));
      dictCode = "MIC_EXHAUST_SOURCE03";
    }
    if (activeTab.value == "SEX中酸碱") {
      tpName = encodeURIComponent(encodeURIComponent("voc/VOC废气在线监测台账-月3.cpt"));
      dictCode = "MIC_EXHAUST_SOURCE04";
    }
  }
  if (reportType.value == "daily") {
    if (activeTab.value == "VOC进口") {
      tpName = encodeURIComponent(encodeURIComponent("voc/VOC废气在线监测台账-日.cpt"));
      dictCode = "MIC_EXHAUST_SOURCE01";
    }
    if (activeTab.value == "VOC出口") {
      tpName = encodeURIComponent(encodeURIComponent("voc/VOC废气在线监测台账-日1.cpt"));
      dictCode = "MIC_EXHAUST_SOURCE02";
    }
    if (activeTab.value == "VOC中酸碱") {
      tpName = encodeURIComponent(encodeURIComponent("voc/VOC废气在线监测台账-日2.cpt"));
      dictCode = "MIC_EXHAUST_SOURCE03";
    }
    if (activeTab.value == "SEX中酸碱") {
      tpName = encodeURIComponent(encodeURIComponent("voc/VOC废气在线监测台账-日3.cpt"));
      dictCode = "MIC_EXHAUST_SOURCE04";
    }
  }
  getSourceValue(dictCode);

  const facCode = localStorage.getItem("facCode");
  let baseUrl = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=${tpName}&user=${username.value}&apiHost=${window.location.protocol}//${window.location.hostname}&facCode=${facCode}`;
  // 获取当前月份第一天
  const firstDayOfMonth = dayjs(new Date(queryParams.year, queryParams.month - 1, 1)).format("YYYY-MM-DD");
  // 获取当前月份最后一天
  const lastDayOfMonth = dayjs(new Date(queryParams.year, queryParams.month, 0)).format("YYYY-MM-DD");
  console.log("start:" + firstDayOfMonth);
  console.log("end:" + lastDayOfMonth);
  let token = getToken().accessToken;
  if (reportType.value == "monthly") {
    baseUrl = `${baseUrl}&startDate=${firstDayOfMonth}&endDate=${lastDayOfMonth}&token=${token}&op=write&__pi__=false`;
  }
  if (reportType.value == "daily") {
    if (!queryParams.date) {
      PxMessage.error("请选择日期");
      return;
    }
    let sd = dayjs(queryParams.date).format("YYYY-MM-DD");
    baseUrl = `${baseUrl}&cdate=${sd}&token=${token}&op=write&__pi__=false`;
  }
  let chartParams = {
    vocType: activeTab.value,
    timeType: reportType.value == "monthly" ? "DAY" : "HOUR",
    timeFrom: reportType.value == "monthly" ? firstDayOfMonth + " 00:00:00" : dayjs(queryParams.date).format("YYYY-MM-DD") + " 00:00:00",
    timeTo: reportType.value == "monthly" ? lastDayOfMonth + " 23:59:59" : dayjs(queryParams.date).format("YYYY-MM-DD") + " 23:59:59"
  };
  getExhaustMeterList(chartParams);
  templateUrl.value = baseUrl;
};
const getSourceValue = async itemValue => {
  let res = await queryNameByTypeCodeAndValue({
    typeCode: "MCTS",
    itemValue
  });
  exhaustSource.value = res;
};
const saveSource = async () => {
  // let obj = {
  //   id: exhaustSource.value.id,
  //   "typeId": "",
  //   "itemName": "",
  //   "itemValue": "",
  //   "itemDesc": "",
  //   "parentId": "",
  //   "itemSort": 0,
  //   "status": ""
  // }
  let res = await dataUpdate({ ...exhaustSource.value, parentId: "MIC_EXHAUST_SOURCE" });
};
const alignData = (list, data) => {
  let t = [];
  list.forEach(v => {
    if (data[v]) {
      t.push(Number(data[v]));
    } else {
      t.push(null);
    }
  });
  return t;
};
const getExhaustMeterList = async params => {
  let serveLoading = null;
  serveLoading = PxLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.5)"
  });
  try {
    let res = await queryExhauseMeterList({
      vocType: params.vocType,
      timeType: params.timeType,
      timeFrom: params.timeFrom,
      timeTo: params.timeTo
    });
    if (serveLoading) {
      serveLoading.close();
    }
    let seriesData = [];
    if (res[1] && res[1].length) {
      res[1].forEach(v => {
        let s_name = codeNameList[params.vocType].filter(s => s.code == v.itemCode)?.[0]?.name;
        let yIndex = 0;
        if (s_name && s_name.indexOf("t/d") != -1) {
          yIndex = 1;
        }
        if (s_name && s_name.indexOf("流量") != -1) {
          yIndex = 2;
        }
        if (s_name) {
          seriesData.push({
            name: s_name,
            type: "line",
            connectNulls: true,
            yAxisIndex: yIndex,
            // smooth: true,
            showSymbol: false,
            data: alignData(res[0], v.itemValue)
          });
        }
      });
    }

    lineOptions.value = {
      title: {
        text: `${params.timeType == "DAY" ? "烟气排放连续监测日平均值" : "烟气排放连续监测小时平均值"}`,
        left: "center",
        top: 0,
        textStyle: {
          fontSize: 16, // 设置字体大小为18像素
          color: "#333", // 可选：设置字体颜色
          fontWeight: "bold" // 可选：设置字体粗细
        }
      },
      tooltip: {
        trigger: "axis"
      },
      legend: {
        data: codeNameList[params.vocType].map(v => v.name),
        top: 22,
        type: "scroll"
      },
      grid: {
        left: "3%",
        right: "3%",
        bottom: "3%",
        top: "20%",
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: params.timeType == "DAY" ? res[0].map(v => dayjs(v).format("YYYY-MM-DD")) : res[0]
      },
      // yAxis: {
      //   type: "value"
      // },
      yAxis: [
        {
          type: "value",
          position: "left",
          axisLine: {
            show: true,
            lineStyle: {
              color: "#313313"
            }
          }
        },
        {
          type: "value",
          name: "t/d",
          position: "right",
          axisLine: {
            show: true,
            lineStyle: {
              color: "#313313"
            }
          },
          axisLabel: {
            textStyle: {
              fontSize: 12 // 字体大小
            }
          }
        },
        {
          type: "value",
          name: "流量",
          position: "right",
          offset: 100,
          axisLine: {
            show: true,
            lineStyle: {
              color: "#313313"
            }
          },
          axisLabel: {
            textStyle: {
              fontSize: 12 // 字体大小
            }
          }
        }
      ],
      series: seriesData
    };
    lineRef.value.updateEchartsOption();
  } catch (error) {
    if (serveLoading) {
      serveLoading.close();
    }
  }
};

onMounted(() => {
  let ym = new Date();
  if (route.query.date) {
    ym = new Date(route.query.date);
  }
  let tmpList = [];
  for (var i = -8; i < 3; i++) {
    let y: number = ym.getFullYear();
    tmpList.push({
      label: y + i,
      value: y + i
    });
  }
  yearList.value = tmpList;
  getUrl();
});

const searchAction = () => {
  getUrl();
};
</script>
<style scoped lang="scss">
.title-content {
  padding: 10px 26px 0;
  // margin-top: 12px;
  background: #fff;

  .title {
    font-size: 22px;
    font-weight: bold;
    text-align: center;
  }

  .sub-text {
    font-size: 16px;
    font-weight: bold;
  }
}

.iframe-content {
  position: relative;
  height: calc(100vh - 410px);
  padding: 16px;
  overflow-y: hidden;
  background: #fff;
}

.template-content {
  width: 100%;
  background-color: #fff;
}

.custom-form-ui {
  height: 38px;

  .px-form-item {
    margin-bottom: 0;
  }
}

.op-btns {
  display: flex;
  padding: 16px;
  margin: 5px 0;
  background-color: #fff;

  .left {
    flex: 1;
    text-align: left;
  }

  .center {
    flex: 1;
    text-align: center;
  }

  .right {
    flex: 1;
    text-align: right;
  }
}

.footer-btns {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  height: 100%;
  padding: 16px;
}

:deep(.echarts-chart) {
  height: 405px;
  padding: 0;

  .echarts-chart-com {
    height: 100%;
    margin-top: 12px;
  }
}

.chartsdom {
  width: 100%;
  height: 405px;
  background: white;

  > div {
    height: 100%;
  }
}
</style>
